package com.udaos.modules.api.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class DownloadURLFileUtils {
	
    @SuppressWarnings("resource")
	public static File downloadFromUrl(String urlStr,String name,String ext) throws IOException {  
  
    	 URL url = new URL(urlStr);    
         HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
         conn.setConnectTimeout(5*1000);  
         //防止屏蔽程序抓取而返回403错误  
         conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
   
         //得到输入流  
         InputStream inputStream = conn.getInputStream();   
         
         FileOutputStream fos = null;
         File tmpFile;
         tmpFile = File.createTempFile(name, '.' + ext);
         tmpFile.deleteOnExit();
         fos = new FileOutputStream(tmpFile);
         int read = 0;
         byte[] bytes = new byte[1024 * 100];
         while ((read = inputStream.read(bytes)) != -1) {
            fos.write(bytes, 0, read);
         }
         fos.flush();
         return tmpFile;
    }  
    
    public static void main(String[] args) {
    	try {
    		File i=downloadFromUrl("http://pic33.nipic.com/20130916/3420027_192919547000_2.jpg","test","jpg");
			System.out.println(i.getName());
			System.out.println(i.length());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
      

}
